<!DOCTYPE html><html class="theme-next gemini use-motion" lang="zh-Hans"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1"><meta name="theme-color" content="#222"><script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script><link href="//cdn.bootcss.com/pace/1.0.2/themes/pink/pace-theme-flash.css" rel="stylesheet"><style>.pace .pace-progress{background:#1e92fb;height:3px}.pace .pace-progress-inner{box-shadow:0 0 10px #1e92fb,0 0 5px #1e92fb}.pace .pace-activity{border-top-color:#1e92fb;border-left-color:#1e92fb}</style><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css"><link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css"><link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css"><link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4"><link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico?v=5.1.4"><link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4"><link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222"><meta name="keywords" content="JavaScript,面试题,"><link rel="alternate" href="/atom.xml" title="It is written" type="application/atom+xml"><meta name="description" content="自我感觉这些题很有用。题目来自： https:&#x2F;&#x2F;www.toptal.com&#x2F;javascript&#x2F;interview-questions#form"><meta property="og:type" content="article"><meta property="og:title" content="37个基本 JavaScript 的面试问题"><meta property="og:url" content="http://king-xiyu.gitee.io/article/e55b4f5b.html"><meta property="og:site_name" content="It is written"><meta property="og:description" content="自我感觉这些题很有用。题目来自： https:&#x2F;&#x2F;www.toptal.com&#x2F;javascript&#x2F;interview-questions#form"><meta property="article:published_time" content="2020-07-07T11:51:19.000Z"><meta property="article:modified_time" content="2020-09-01T00:45:13.774Z"><meta property="article:author" content="King-XiYu"><meta property="article:tag" content="JavaScript"><meta property="article:tag" content="面试题"><meta name="twitter:card" content="summary"><script type="text/javascript" id="hexo.configurations">var NexT=window.NexT||{},CONFIG={root:"/",scheme:"Gemini",version:"5.1.4",sidebar:{position:"left",display:"post",offset:12,b2t:!0,scrollpercent:!0,onmobile:!1},fancybox:!0,tabs:!0,motion:{enable:!0,async:!1,transition:{post_block:"fadeIn",post_header:"slideDownIn",post_body:"slideDownIn",coll_header:"slideLeftIn",sidebar:"slideUpIn"}},duoshuo:{userId:"0",author:"博主"},algolia:{applicationID:"",apiKey:"",indexName:"",hits:{per_page:10},labels:{input_placeholder:"Search for Posts",hits_empty:"We didn't find any results for the search: ${query}",hits_stats:"${hits} results found in ${time} ms"}}}</script><link rel="canonical" href="http://king-xiyu.gitee.io/article/e55b4f5b.html"><title>37个基本 JavaScript 的面试问题 | It is written</title><meta name="generator" content="Hexo 4.2.0"></head><body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans"><div class="container sidebar-position-left page-post-detail"><div class="headband"></div><header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="header-inner"><div class="site-brand-wrapper"><div class="site-meta"><div class="custom-logo-site-title"><a href="/" class="brand" rel="start"><span class="logo-line-before"><i></i></span> <span class="site-title">It is written</span><span class="logo-line-after"><i></i></span></a></div><p class="site-subtitle"></p></div><div class="site-nav-toggle"> <button><span class="btn-bar"></span><span class="btn-bar"></span><span class="btn-bar"></span></button></div></div><nav class="site-nav"><ul id="menu" class="menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i><br> 首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i><br> 标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i><br> 分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i><br> 归档</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i><br> 关于</a></li><li class="menu-item menu-item-search"><a href="javascript:;" class="popup-trigger"><i class="menu-item-icon fa fa-search fa-fw"></i><br> 搜索</a></li></ul><div class="site-search"><div class="popup search-popup local-search-popup"><div class="local-search-header clearfix"><span class="search-icon"><i class="fa fa-search"></i></span><span class="popup-btn-close"><i class="fa fa-times-circle"></i></span><div class="local-search-input-wrapper"> <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input"></div></div><div id="local-search-result"></div></div></div></nav></div></header><main id="main" class="main"><div class="main-inner"><div class="content-wrap"><div id="content" class="content"><div id="posts" class="posts-expand"><article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"><div class="post-block"><link itemprop="mainEntityOfPage" href="http://king-xiyu.gitee.io/article/e55b4f5b.html"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="name" content="King-XiYu"><meta itemprop="description" content=""><meta itemprop="image" content="http://ww1.sinaimg.cn/large/007WurYGgy1ge8nxttd9nj302s02s0si.jpg"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="It is written"></span><header class="post-header"><h1 class="post-title" itemprop="name headline">37个基本 JavaScript 的面试问题</h1><div class="post-meta"><span class="post-time"><span class="post-meta-item-icon"><i class="fa fa-calendar-o"></i></span> <span class="post-meta-item-text">发表于</span> <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-07-07T19:51:19+08:00">2020-07-07</time> <span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-calendar-check-o"></i></span> <span class="post-meta-item-text">更新于&#58;</span> <time title="更新于" itemprop="dateModified" datetime="2020-09-01T08:45:13+08:00">2020-09-01</time></span> <span class="post-category"><span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-folder-o"></i></span> <span class="post-meta-item-text">分类于</span> <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/%E6%8A%80%E6%9C%AF%E6%A0%88/" itemprop="url" rel="index"><span itemprop="name">技术栈</span></a></span> ， <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/%E6%8A%80%E6%9C%AF%E6%A0%88/JavaScript/" itemprop="url" rel="index"><span itemprop="name">JavaScript</span></a></span> ， <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/%E6%8A%80%E6%9C%AF%E6%A0%88/JavaScript/%E9%9D%A2%E8%AF%95%E9%A2%98/" itemprop="url" rel="index"><span itemprop="name">面试题</span></a></span></span> <span class="post-comments-count"><span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-comment-o"></i></span><a href="/article/e55b4f5b.html#comments" itemprop="discussionUrl"><span class="post-comments-count valine-comment-count" data-xid="/article/e55b4f5b.html" itemprop="commentCount"></span></a></span> <span id="/article/e55b4f5b.html" class="leancloud_visitors" data-flag-title="37个基本 JavaScript 的面试问题"><span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-eye"></i></span> <span class="post-meta-item-text">阅读次数&#58;</span><span class="leancloud-visitors-count"></span></span><div class="post-wordcount"><span class="post-meta-item-icon"><i class="fa fa-file-word-o"></i></span> <span class="post-meta-item-text">字数统计&#58;</span> <span title="字数统计">4.7k 字</span> <span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-clock-o"></i></span> <span class="post-meta-item-text">阅读时长 &asymp;</span> <span title="阅读时长">18 分钟</span></div></div></header><div class="post-body" itemprop="articleBody"><p>自我感觉这些题很有用。<br>题目来自： <a href="https://www.toptal.com/javascript/interview-questions#form" target="_blank" rel="noopener">https://www.toptal.com/javascript/interview-questions#form</a></p><a id="more"></a><h1 id="使用-typeof-bar-quot-object-quot-来确定bar是否是对象的潜在陷阱是什么-怎样才能避免这个陷阱呢"><a href="#使用-typeof-bar-quot-object-quot-来确定bar是否是对象的潜在陷阱是什么-怎样才能避免这个陷阱呢" class="headerlink" title="使用 typeof bar === &quot;object&quot; 来确定bar是否是对象的潜在陷阱是什么?怎样才能避免这个陷阱呢?"></a>使用 <code>typeof bar === &quot;object&quot;</code> 来确定bar是否是对象的潜在陷阱是什么?怎样才能避免这个陷阱呢?</h1><p>答：</p><p>虽然 <code>typeof bar === &quot;object&quot;</code> 是检查 <code>bar</code> 是否是对象的可靠方法，但JavaScript中令人惊讶的问题是 <code>null</code> 也被认为是对象!</p><p>因此，令大多数开发人员惊讶的是，下面的代码将 <code>true</code> (而不是 <code>false</code> )记录到控制台</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> bar = <span class="literal">null</span>;</span><br><span class="line"><span class="built_in">console</span>.log(<span class="keyword">typeof</span> bar === <span class="string">"object"</span>);  <span class="comment">// true</span></span><br></pre></td></tr></table></figure><p>只要意识到这一点，也可以通过检查 <code>bar</code> 是否为空来轻松避免这个问题</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(bar !== <span class="literal">null</span>) &amp;&amp; (<span class="keyword">typeof</span> bar === <span class="string">'object'</span>); <span class="comment">// false</span></span><br></pre></td></tr></table></figure><p>为了使我们的回答更加彻底，还有两件事值得注意:</p><p>首先，如果 <code>bar</code> 是一个函数，上面的解决方案将返回 <code>false</code> 。在大多数情况下，这是所需的行为，但是在您希望为函数返回 <code>true</code> 的情况下，您可以将上述解决方案修改为:</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log((bar !== <span class="literal">null</span>) &amp;&amp; ((<span class="keyword">typeof</span> bar === <span class="string">"object"</span>) || (<span class="keyword">typeof</span> bar === <span class="string">"function"</span>)));</span><br></pre></td></tr></table></figure><p>其次，如果 <code>bar</code> 是数组，上面的解决方案将返回 <code>true</code> (例如，如果<code>var bar =[];</code> )。在大多数情况下，这是所需的行为，因为数组确实是对象，但在您希望数组也为 <code>false</code> 的情况下，您可以将上述解决方案修改为:</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log((bar !== <span class="literal">null</span>) &amp;&amp; (<span class="keyword">typeof</span> bar === <span class="string">"object"</span>) &amp;&amp; (toString.call(bar) !== <span class="string">"[object Array]"</span>));</span><br></pre></td></tr></table></figure><p>但是，还有另一种方法，对于null、数组和函数返回 <code>false</code> ，但是对于对象返回 <code>true</code> :</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log((bar !== <span class="literal">null</span>) &amp;&amp; (bar.constructor === <span class="built_in">Object</span>));</span><br></pre></td></tr></table></figure><p>或者，如果您使用的是jQuery：</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log((bar !== <span class="literal">null</span>) &amp;&amp; (<span class="keyword">typeof</span> bar === <span class="string">"object"</span>) &amp;&amp; (! $.isArray(bar)));</span><br></pre></td></tr></table></figure><p>扩展：ES5使数组的情况相当简单，包括它自己的空检查:</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="built_in">Array</span>.isArray(bar));</span><br></pre></td></tr></table></figure><br><h1 id="下面的代码将输出什么到控制台，为什么？"><a href="#下面的代码将输出什么到控制台，为什么？" class="headerlink" title="下面的代码将输出什么到控制台，为什么？"></a>下面的代码将输出什么到控制台，为什么？</h1><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="keyword">var</span> a = b = <span class="number">3</span>;</span><br><span class="line">&#125;)();</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">"a defined? "</span> + (<span class="keyword">typeof</span> a !== <span class="string">'undefined'</span>));</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">"b defined? "</span> + (<span class="keyword">typeof</span> b !== <span class="string">'undefined'</span>));</span><br></pre></td></tr></table></figure><p>答：</p><p>false 、 true</p><p>由于a和b都是在函数的封闭范围内定义的，并且由于它们所在的行以var关键字开头，大多数JavaScript开发人员会认为在上面的示例中a和b都是未定义的。</p><p>但是，事实并非如此。 这里的问题是，大多数开发人员错误地理解了语句 <code>var a = b = 3</code>； 简写为：</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> b = <span class="number">3</span>;</span><br><span class="line"><span class="keyword">var</span> a = b;</span><br></pre></td></tr></table></figure><p>但实际上，<code>var a = b = 3</code> ; 实际上是：</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">b = <span class="number">3</span>;</span><br><span class="line"><span class="keyword">var</span> a = b;</span><br></pre></td></tr></table></figure><p>因此(如果您没有使用strict模式)，代码段的输出将是</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">a defined? <span class="literal">false</span></span><br><span class="line">b defined? <span class="literal">true</span></span><br></pre></td></tr></table></figure><p>但是b如何被定义在封闭函数的范围之外?</p><p>因为 <code>var a = b = 3;</code> 是表述 <code>b = 3;var a = b;</code> 的简写;， b最终是一个全局变量(因为它前面没有var关键字)，因此它仍然在作用域中，甚至在封闭函数之外。</p><p>注意，在严格模式下(即语句<code>var a = b = 3;</code>将生成一个运行时错误 <code>ReferenceError: b is not defined</code> ，从而避免任何可能导致错误的<code>headfakes/bug</code> 。(这是为什么在代码中使用use strict的另一个主要例子!)</p><br><h1 id="下面的代码将输出什么到控制台，为什么？-1"><a href="#下面的代码将输出什么到控制台，为什么？-1" class="headerlink" title="下面的代码将输出什么到控制台，为什么？"></a>下面的代码将输出什么到控制台，为什么？</h1><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> myObject = &#123;</span><br><span class="line">    foo: <span class="string">"bar"</span>,</span><br><span class="line">    func: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> self = <span class="keyword">this</span>;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">"outer func:  this.foo = "</span> + <span class="keyword">this</span>.foo);</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">"outer func:  self.foo = "</span> + self.foo);</span><br><span class="line">        (<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"inner func:  this.foo = "</span> + <span class="keyword">this</span>.foo);</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"inner func:  self.foo = "</span> + self.foo);</span><br><span class="line">        &#125;());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line">myObject.func();</span><br></pre></td></tr></table></figure><p>答：</p><p><code>1.outer func: this.foo = bar 2.outer func: self.foo = bar 3.inner func: this.foo = undefined 4.inner func: self.foo = bar</code></p><p>在外部函数中，<code>this</code> 和 <code>self</code> 都引用 <code>myObject</code>，因此都可以正确地引用和访问 <code>foo</code>。</p><p>但是，在内部函数中，<code>this</code> 不再引用 <code>myObject</code> 。因此，<code>this.foo</code> 在内部函数中未定义，而对局部变量 <code>self</code> 的引用仍然在作用域中，并且可以在该处访问。</p><br><h1 id="将JavaScript源文件的整个内容包装在函数块中的意义和原因是什么？"><a href="#将JavaScript源文件的整个内容包装在函数块中的意义和原因是什么？" class="headerlink" title="将JavaScript源文件的整个内容包装在函数块中的意义和原因是什么？"></a>将JavaScript源文件的整个内容包装在函数块中的意义和原因是什么？</h1><p>答：</p><p>这种技术的目的是将代码包装在功能范围。</p><p>它有助于减少以下机会：</p><ul><li>与其他应用程序/库发生冲突</li><li>污染优势(全局最有可能)范围</li></ul><p>这是一种越来越普遍的做法，被许多流行的JavaScript库（jQuery，Node.js等）采用。 这种技术会在文件的整个内容周围创建一个闭合符，这可能是最重要的是创建一个私有名称空间，从而有助于避免不同的JavaScript模块和库之间可能出现的名称冲突。</p><p>此技术的另一个功能是允许为全局变量提供易于引用的别名（可能较短）。 例如，这通常在jQuery插件中使用。 jQuery允许您使用 <code>jQuery.noConflict（）</code> 禁用对jQuery名称空间的$引用。 如果已完成此操作，则您的代码仍可以使用 <code>$</code> 并采用此关闭技术，如下所示：</p><p><code>(function($) { /* jQuery plugin code referencing $ */ } )(jQuery);</code></p><br><h1 id="在JavaScript源文件开头包含use-strict的意义和好处是什么？"><a href="#在JavaScript源文件开头包含use-strict的意义和好处是什么？" class="headerlink" title="在JavaScript源文件开头包含use strict的意义和好处是什么？"></a>在JavaScript源文件开头包含<code>use strict</code>的意义和好处是什么？</h1><p>答：</p><p>开启js的严格模式；好处：消除Javascript语法的一些不合理、不严谨之处，减少一些怪异行为</p><p><code>use strict</code> 是一种在运行时强制对JavaScript代码执行更严格的解析和错误处理的方法。那些本来会被忽略或以静默方式失败的代码错误现在将生成错误或抛出异常。一般来说，这是一个好的做法。</p><p>严格模式的一些主要好处包括：</p><ul><li><p><strong>更容易调试。</strong>那些本来会被忽略或悄无声息地失败的代码错误现在将生成错误或抛出异常，更快地提醒您代码中的问题并引导您更快地找到它们的源代码。</p></li><li><p><strong>防止意外的全局变量。</strong> 如果没有严格模式，则将值分配给未声明的变量会自动创建一个具有该名称的全局变量。 这是JavaScript中最常见的错误之一。 在严格模式下，尝试执行此操作将引发错误。</p></li><li><p><strong>消除 <code>this</code> 强制性。</strong> 如果没有严格模式，则对此null或undefined的 <code>this</code> 值的引用将自动强制为全局值。 这可能会导致许多假冒和拔出头发的错误。 在严格模式下，引用一个 <code>this</code> 值为空或未定义将引发错误。</p></li><li><p><strong>不允许重复的参数值。</strong> 严格模式在检测到某个函数的重复命名参数（例如，<code>function foo（val1，val2，val1）{}</code>）时会引发错误，从而几乎可以肯定是代码中的错误，否则可能会浪费很多 时间追踪。</p><ul><li>注意:以前(在ECMAScript 5中)严格的模式会禁止重复的属性名(例如<code>var object = {foo: &quot;bar&quot;， foo: &quot;baz&quot;};</code>)，但是在ECMAScript 2015中，这种情况已经不复存在了。</li></ul></li><li><p><strong>使eval()更安全。</strong><code>eval()</code> 在严格模式和非严格模式下的行为方式有一些不同。最重要的是，在严格模式下，<code>eval()</code> 语句中声明的变量和函数不会在包含范围内创建(它们是在非严格模式下在包含范围内创建的，这也可能是常见问题的根源)。</p></li><li><p>在无效使用 <code>delete</code> 时抛出错误。<code>delete</code> 操作符(用于从对象中删除属性)不能用于对象的不可配置属性。当尝试删除不可配置的属性时，非严格模式将悄无声息地失败，而在这种情况下，严格模式将抛出错误。</p></li></ul><br><h1 id="考虑下面的两个函数。它们会返回相同的东西吗-为什么或为什么不？"><a href="#考虑下面的两个函数。它们会返回相同的东西吗-为什么或为什么不？" class="headerlink" title="考虑下面的两个函数。它们会返回相同的东西吗?为什么或为什么不？"></a>考虑下面的两个函数。它们会返回相同的东西吗?为什么或为什么不？</h1><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo1</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">      bar: <span class="string">"hello"</span></span><br><span class="line">  &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo2</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="keyword">return</span></span><br><span class="line">  &#123;</span><br><span class="line">      bar: <span class="string">"hello"</span></span><br><span class="line">  &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>答：</p><p>不会返回相同的东西；</p><p>foo1 返回： bar:”hello”</p><p>foo2 返回： undefined</p><p>因为foo2的return换行了。</p><p>官方参考：</p><p>令人惊讶的是，这两个函数不会返回相同的东西。 而是：</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="string">"foo1 returns:"</span>);</span><br><span class="line"><span class="built_in">console</span>.log(foo1());</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">"foo2 returns:"</span>);</span><br><span class="line"><span class="built_in">console</span>.log(foo2());</span><br></pre></td></tr></table></figure><p>将产生：</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">foo1 returns:</span><br><span class="line"><span class="built_in">Object</span> &#123;<span class="attr">bar</span>: <span class="string">"hello"</span>&#125;</span><br><span class="line">foo2 returns:</span><br><span class="line"><span class="literal">undefined</span></span><br></pre></td></tr></table></figure><p>这不仅令人惊讶，而且使其特别粗糙的是，foo2()返回undefined而不会抛出任何错误。</p><p>其原因与JavaScript中的分号在技术上是可选的（尽管通常省略分号实际上是一种不好的形式）有关。 结果，当在foo2（）中遇到包含<code>return</code>语句的行（该行上没有其他内容）时，会在return语句后立即自动插入分号。</p><p>因为代码的其余部分是完全有效的，所以即使它没有被调用或做任何事情也不会引发任何错误（它只是一个未使用的代码块，定义了与字符串“ hello”相等的属性栏）。</p><p>这种行为还要求遵循JavaScript中在行尾而不是在新行开始处放置左花括号的惯例。如这里所示，这不仅仅是JavaScript的一种风格偏好。</p><br><h1 id="NaN-是什么-它是什么类型的-如何可靠地测试一个值是否等于NaN"><a href="#NaN-是什么-它是什么类型的-如何可靠地测试一个值是否等于NaN" class="headerlink" title="NaN 是什么?它是什么类型的?如何可靠地测试一个值是否等于NaN?"></a><code>NaN</code> 是什么?它是什么类型的?如何可靠地测试一个值是否等于<code>NaN</code>?</h1><p>答：</p><p><code>NaN</code> 是 Not a Number（不是一个数字）；一些不合理的数学运算时会得到 <code>NaN</code>。</p><p>它是 number 类型。</p><p>官方参考：</p><p>NaN属性表示一个“不是数字”的值。这个特殊的值来自于一个操作数无法执行的操作，因为其中一个操作数是非数字的(例如“abc”/ 4)，或者因为操作的结果是非数字的。</p><p>虽然这看起来很简单，但NaN有一些令人吃惊的特征，如果你没有意识到，它们可能会导致揪头发的错误。</p><p>首先，尽管NaN不是数字，但信不信由你，它的类型是数字:</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="keyword">typeof</span> <span class="literal">NaN</span> === <span class="string">"number"</span>);  <span class="comment">// true</span></span><br></pre></td></tr></table></figure><p>此外，NaN可以与任何东西相比较——甚至是它自己!——是错误的:</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="literal">NaN</span> === <span class="literal">NaN</span>);  <span class="comment">// false</span></span><br></pre></td></tr></table></figure><p>测试一个数字是否等于NaN的一种半可靠的方法是使用内置函数isNaN()，但是即使使用isNaN()也是一种不完美的解决方案。</p><p>更好的解决方案是使用 <code>value !== value</code>，只有当值等于NaN时才会产生true。此外，ES6提供了一个新的 <code>Number.isNaN()</code> 函数，它与旧的全局isNaN()函数不同，而且更可靠。</p><br><h1 id="下面的代码将输出什么-解释你的答案。"><a href="#下面的代码将输出什么-解释你的答案。" class="headerlink" title="下面的代码将输出什么?解释你的答案。"></a>下面的代码将输出什么?解释你的答案。</h1><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="number">0.1</span> + <span class="number">0.2</span>);</span><br><span class="line"><span class="built_in">console</span>.log(<span class="number">0.1</span> + <span class="number">0.2</span> == <span class="number">0.3</span>);</span><br></pre></td></tr></table></figure><p>答：</p><p>不确定；可能是0.3 ,或者是0.3333…</p><p>不确定；可能是false也有可能是true</p><p>官方参考：</p><p>对这个问题的一个有见地的回答是:你不能肯定。它可能会打印出0.3和true，也可能不会。JavaScript中的数字都是用浮点精度处理的，因此，可能并不总是产生预期的结果。上面提供的示例是演示这个问题的经典案例。令人惊讶的是，它会被打印出来：</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">0.30000000000000004</span></span><br><span class="line"><span class="literal">false</span></span><br></pre></td></tr></table></figure><p>一个典型的解决方法是用特殊的常数比较两个数之间的绝对差：</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">areTheNumbersAlmostEqual</span>(<span class="params">num1, num2</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="built_in">Math</span>.abs(num1 - num2) &lt; <span class="built_in">Number</span>.EPSILON;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(areTheNumbersAlmostEqual(<span class="number">0.1</span> + <span class="number">0.2</span>, <span class="number">0.3</span>));</span><br></pre></td></tr></table></figure><br><h1 id="讨论如何编写一个isInteger-x-函数来确定x是否是整数。"><a href="#讨论如何编写一个isInteger-x-函数来确定x是否是整数。" class="headerlink" title="讨论如何编写一个isInteger(x)函数来确定x是否是整数。"></a>讨论如何编写一个<code>isInteger(x)</code>函数来确定<code>x</code>是否是整数。</h1><p>这听起来可能很琐碎，实际上，对于ECMAscript 6来说，这一点很琐碎，因为它引入了一个新的 <code>Number.isInteger()</code> 函数，正是为了这个目的。但是，在ECMAScript 6之前，这有点复杂，因为没有提供与 <code>Number.isInteger()</code> 方法等价的方法。</p><p>问题在于，在ECMAScript规范中，整数仅在概念上存在。 即数字值始终存储为浮点值。</p><p>考虑到这一点，最简单和干净的前ecmascript -6解决方案(它也足够健壮，即使非数字值，如字符串或null被传递给函数，也会返回false)将是以下使用的位XOR操作符:</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isInteger</span>(<span class="params">x</span>) </span>&#123; <span class="keyword">return</span> (x ^ <span class="number">0</span>) === x; &#125;</span><br></pre></td></tr></table></figure><p>下面的解决方案也可以，尽管不如上面的解决方案优雅：</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isInteger</span>(<span class="params">x</span>) </span>&#123; <span class="keyword">return</span> <span class="built_in">Math</span>.round(x) === x; &#125;</span><br></pre></td></tr></table></figure><p>注意，在上面的实现中，<code>Math.ceil()</code> 或 <code>Math.floor()</code> 同样可以很好地使用(而不是 <code>Math.round())</code>。或者</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isInteger</span>(<span class="params">x</span>) </span>&#123; <span class="keyword">return</span> (<span class="keyword">typeof</span> x === <span class="string">'number'</span>) &amp;&amp; (x % <span class="number">1</span> === <span class="number">0</span>); &#125;</span><br></pre></td></tr></table></figure><p>以下是一种很常见的错误解决方案：</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isInteger</span>(<span class="params">x</span>) </span>&#123; <span class="keyword">return</span> <span class="built_in">parseInt</span>(x, <span class="number">10</span>) === x; &#125;</span><br></pre></td></tr></table></figure><p>虽然这种基于解析的方法可以很好地处理许多 <code>x</code> 值，但是一旦 <code>x</code> 变得非常大，它就不能正常工作。问题是 <code>parseInt()</code> 在解析数字之前将其第一个参数强制转换为字符串。因此，一旦数字足够大，它的字符串表示将以指数形式(例如，<code>1e+21</code> )表示。相应地，<code>parseInt()</code> 将尝试解析 <code>1e+21</code>，但当它到达<code>e</code>字符时将停止解析，因此将返回值1。请注意:</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&gt; <span class="built_in">String</span>(<span class="number">1000000000000000000000</span>)</span><br><span class="line"><span class="string">'1e+21'</span></span><br><span class="line"></span><br><span class="line">&gt; <span class="built_in">parseInt</span>(<span class="number">1000000000000000000000</span>, <span class="number">10</span>)</span><br><span class="line"><span class="number">1</span></span><br><span class="line"></span><br><span class="line">&gt; <span class="built_in">parseInt</span>(<span class="number">1000000000000000000000</span>, <span class="number">10</span>) === <span class="number">1000000000000000000000</span></span><br><span class="line"><span class="literal">false</span></span><br></pre></td></tr></table></figure><br><h1 id="执行以下代码时，数字1-4将以什么顺序记录到控制台？-为什么？"><a href="#执行以下代码时，数字1-4将以什么顺序记录到控制台？-为什么？" class="headerlink" title="执行以下代码时，数字1-4将以什么顺序记录到控制台？ 为什么？"></a>执行以下代码时，数字1-4将以什么顺序记录到控制台？ 为什么？</h1><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="number">1</span>); </span><br><span class="line">    setTimeout(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;<span class="built_in">console</span>.log(<span class="number">2</span>)&#125;, <span class="number">1000</span>); </span><br><span class="line">    setTimeout(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;<span class="built_in">console</span>.log(<span class="number">3</span>)&#125;, <span class="number">0</span>); </span><br><span class="line">    <span class="built_in">console</span>.log(<span class="number">4</span>);</span><br><span class="line">&#125;)();</span><br></pre></td></tr></table></figure><p>答：</p><p>1432，因为1和4是同步的，2和3是异步，先执行同步后执行异步，同步的代码从上往下执行，3是定时器立即执行，2是等一秒后执行的。</p><p>官方参考：</p><p>这些值将按以下顺序被记录：</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span></span><br><span class="line"><span class="number">4</span></span><br><span class="line"><span class="number">3</span></span><br><span class="line"><span class="number">2</span></span><br></pre></td></tr></table></figure><p>首先，让我们解释一下可能更明显的部分：</p><ul><li><p>首先显示1和4，因为它们是通过简单调用console.log()记录的，没有任何延迟</p></li><li><p>2在3后面显示，因为2在1000毫秒（即1秒）的延迟后被记录，而3在0毫秒的延迟后被记录。</p></li></ul><p>好的。 但是，如果在延迟0毫秒后记录3，这是否意味着它马上就被记录了？ 而且，如果是这样，由于4由后面的代码行记录，因此不应该在4之前记录吗？</p><p>答案与正确理解JavaScript事件和时间有关。</p><p>浏览器具有事件循环，该循环检查事件队列并处理未决事件。 例如，如果某个事件在浏览器繁忙（例如，处理onclick）时在后台发生（例如，脚本onload事件），则该事件将附加到队列中。 当onclick处理程序完成时，将检查队列，然后处理事件（例如，执行<code>onload</code> 脚本）。</p><p>同样，如果浏览器忙，则 <code>setTimeout()</code> 还将其引用函数的执行放入事件队列中。</p><p>当一个0值作为第二个参数传递给 <code>setTimeout()</code> 时，它尝试“尽快”执行指定的函数。具体来说，函数的执行被放在事件队列上，以便在下一个计时器滴答时发生。但请注意，这并不是即时的;该函数直到下一个滴答才执行。这就是为什么在上面的示例中，对 <code>console.log(4)</code> 的调用发生在对 <code>console.log(3)</code> 的调用之前(因为对 <code>console.log(3)</code> 的调用是通过 <code>setTimeout</code> 调用的，所以会稍微延迟)。</p><br><h1 id="编写一个简单的函数-小于160个字符-，返回一个布尔值，指示字符串是否是回文。"><a href="#编写一个简单的函数-小于160个字符-，返回一个布尔值，指示字符串是否是回文。" class="headerlink" title="编写一个简单的函数(小于160个字符)，返回一个布尔值，指示字符串是否是回文。"></a>编写一个简单的函数(小于160个字符)，返回一个布尔值，指示字符串是否是回文。</h1><p>如果str是回文，下面一行函数将返回true;否则，返回false。</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isPalindrome</span>(<span class="params">str</span>) </span>&#123;</span><br><span class="line">  str = str.replace(<span class="regexp">/\W/g</span>, <span class="string">''</span>).toLowerCase();</span><br><span class="line">  <span class="keyword">return</span> (str == str.split(<span class="string">''</span>).reverse().join(<span class="string">''</span>));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>比如：</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(isPalindrome(<span class="string">"level"</span>)); <span class="comment">// true</span></span><br><span class="line"><span class="built_in">console</span>.log(isPalindrome(<span class="string">"levels"</span>)); <span class="comment">// true</span></span><br><span class="line"><span class="built_in">console</span>.log(isPalindrome(<span class="string">"A car, a man, a maraca"</span>)); <span class="comment">// true</span></span><br></pre></td></tr></table></figure><br><h1 id="编写一个-sum-方法，当使用以下两种语法调用时，该方法将正常工作。"><a href="#编写一个-sum-方法，当使用以下两种语法调用时，该方法将正常工作。" class="headerlink" title="编写一个 sum 方法，当使用以下两种语法调用时，该方法将正常工作。"></a>编写一个 <code>sum</code> 方法，当使用以下两种语法调用时，该方法将正常工作。</h1><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(sum(<span class="number">2</span>,<span class="number">3</span>));   <span class="comment">// Outputs 5</span></span><br><span class="line"><span class="built_in">console</span>.log(sum(<span class="number">2</span>)(<span class="number">3</span>));  <span class="comment">// Outputs 5</span></span><br></pre></td></tr></table></figure><p>至少有两种方法可以做到这一点：</p><p><strong>方法一</strong></p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sum</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (<span class="built_in">arguments</span>.length == <span class="number">2</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">arguments</span>[<span class="number">0</span>] + <span class="built_in">arguments</span>[<span class="number">1</span>];</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">y</span>) </span>&#123; <span class="keyword">return</span> x + y; &#125;;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在JavaScript中，函数提供对arguments对象的访问，而该object提供对传递给函数的实际参数的访问。 这使我们能够使用length属性在运行时确定传递给函数的参数数量。</p><p>如果传递了两个参数，我们只需将它们相加并返回。</p><p>否则，我们假设它是以sum(2)(3)的形式调用的，因此我们返回一个匿名函数，该函数将传递给sum()(本例中为2)的参数和传递给匿名函数(本例中为3)的参数相加。</p><p><strong>方法二</strong></p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sum</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (y !== <span class="literal">undefined</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> x + y;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">y</span>) </span>&#123; <span class="keyword">return</span> x + y; &#125;;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>当调用函数时，JavaScript不需要参数的数量来匹配函数定义中的参数数量。如果传递的参数数量超过了函数定义中的参数数量，那么多余的参数将被忽略。另一方面，如果传递的参数数量小于函数定义中的参数数量，那么丢失的参数在函数中引用时的值将为undefined。因此，在上面的示例中，只需检查第二个参数是否未定义，我们就可以确定调用函数的方式并相应地进行。</p><h1 id="考虑以下代码片段：-a-当用户单击按钮4时，控制台记录了什么内容以及为什么？-b-提供一个或多个可按预期工作的替代实现。"><a href="#考虑以下代码片段：-a-当用户单击按钮4时，控制台记录了什么内容以及为什么？-b-提供一个或多个可按预期工作的替代实现。" class="headerlink" title="考虑以下代码片段：(a)当用户单击按钮4时，控制台记录了什么内容以及为什么？(b)提供一个或多个可按预期工作的替代实现。"></a>考虑以下代码片段：(a)当用户单击按钮4时，控制台记录了什么内容以及为什么？(b)提供一个或多个可按预期工作的替代实现。</h1><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">  <span class="keyword">var</span> btn = <span class="built_in">document</span>.createElement(<span class="string">'button'</span>);</span><br><span class="line">  btn.appendChild(<span class="built_in">document</span>.createTextNode(<span class="string">'Button '</span> + i));</span><br><span class="line">  btn.addEventListener(<span class="string">'click'</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123; <span class="built_in">console</span>.log(i); &#125;);</span><br><span class="line">  <span class="built_in">document</span>.body.appendChild(btn);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>官方参考：</p><p>(a) 无论用户单击哪个按钮，数字5始终都会记录到控制台。 这是因为，在调用onclick方法（对于任何按钮）时，for循环已经完成，并且变量i已经具有5的值。（如果受访者知道足够多的话，可以给他们加分） 有关执行上下文，变量对象，激活对象和内部“作用域”属性如何影响关闭行为的信息。）</p><p>(b) 实现这一点的关键是在每次通过for循环时捕获i的值，将其传递到一个新创建的函数对象中。这里有四种可能的方法来实现这一点.</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">  <span class="keyword">var</span> btn = <span class="built_in">document</span>.createElement(<span class="string">'button'</span>);</span><br><span class="line">  btn.appendChild(<span class="built_in">document</span>.createTextNode(<span class="string">'Button '</span> + i));</span><br><span class="line">  btn.addEventListener(<span class="string">'click'</span>, (<span class="function"><span class="keyword">function</span>(<span class="params">i</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123; <span class="built_in">console</span>.log(i); &#125;;</span><br><span class="line">  &#125;)(i));</span><br><span class="line">  <span class="built_in">document</span>.body.appendChild(btn);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>或者，您可以将整个调用打包到 <code>btn.addEventListener</code> 中的新匿名函数:</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">  <span class="keyword">var</span> btn = <span class="built_in">document</span>.createElement(<span class="string">'button'</span>);</span><br><span class="line">  btn.appendChild(<span class="built_in">document</span>.createTextNode(<span class="string">'Button '</span> + i));</span><br><span class="line">  (<span class="function"><span class="keyword">function</span> (<span class="params">i</span>) </span>&#123;</span><br><span class="line">    btn.addEventListener(<span class="string">'click'</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123; <span class="built_in">console</span>.log(i); &#125;);</span><br><span class="line">  &#125;)(i);</span><br><span class="line">  <span class="built_in">document</span>.body.appendChild(btn);</span><br></pre></td></tr></table></figure><p>或者，我们可以用对数组对象的本机 <code>forEach</code> 方法的调用来替换 <code>for</code> 循环:</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">[<span class="string">'a'</span>, <span class="string">'b'</span>, <span class="string">'c'</span>, <span class="string">'d'</span>, <span class="string">'e'</span>].forEach(<span class="function"><span class="keyword">function</span> (<span class="params">value, i</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> btn = <span class="built_in">document</span>.createElement(<span class="string">'button'</span>);</span><br><span class="line">  btn.appendChild(<span class="built_in">document</span>.createTextNode(<span class="string">'Button '</span> + i));</span><br><span class="line">  btn.addEventListener(<span class="string">'click'</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123; <span class="built_in">console</span>.log(i); &#125;);</span><br><span class="line">  <span class="built_in">document</span>.body.appendChild(btn);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure><p>最后，如果你在ES6/ES2015上下文中，最简单的解决方案是使用 <code>let i</code> 而不是 <code>var i</code> :</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">  <span class="keyword">var</span> btn = <span class="built_in">document</span>.createElement(<span class="string">'button'</span>);</span><br><span class="line">  btn.appendChild(<span class="built_in">document</span>.createTextNode(<span class="string">'Button '</span> + i));</span><br><span class="line">  btn.addEventListener(<span class="string">'click'</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123; <span class="built_in">console</span>.log(i); &#125;);</span><br><span class="line">  <span class="built_in">document</span>.body.appendChild(btn);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div><footer class="post-footer"><div class="post-tags"><a href="/tags/JavaScript/" rel="tag"><i class="fa fa-tag"></i> JavaScript</a><a href="/tags/%E9%9D%A2%E8%AF%95%E9%A2%98/" rel="tag"><i class="fa fa-tag"></i> 面试题</a></div><div class="post-nav"><div class="post-nav-next post-nav-item"><a href="/article/8b506fdc.html" rel="next" title="Echarts -- 五分钟入门"><i class="fa fa-chevron-left"></i> Echarts -- 五分钟入门</a></div><span class="post-nav-divider"></span><div class="post-nav-prev post-nav-item"> <a href="/article/85fb390f.html" rel="prev" title="微信小程序开发">微信小程序开发<i class="fa fa-chevron-right"></i></a></div></div></footer></div></article><div class="post-spread"></div></div></div><div class="comments" id="comments"></div></div><div class="sidebar-toggle"><div class="sidebar-toggle-line-wrap"><span class="sidebar-toggle-line sidebar-toggle-line-first"></span><span class="sidebar-toggle-line sidebar-toggle-line-middle"></span><span class="sidebar-toggle-line sidebar-toggle-line-last"></span></div></div><aside id="sidebar" class="sidebar"><div class="sidebar-inner"><ul class="sidebar-nav motion-element"><li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap"> 文章目录</li><li class="sidebar-nav-overview" data-target="site-overview-wrap"> 站点概览</li></ul><section class="site-overview-wrap sidebar-panel"><div class="site-overview"><div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person"> <img class="site-author-image" itemprop="image" src="http://ww1.sinaimg.cn/large/007WurYGgy1ge8nxttd9nj302s02s0si.jpg" alt="King-XiYu"><p class="site-author-name" itemprop="name">King-XiYu</p><p class="site-description motion-element" itemprop="description">有志者事竟成</p></div><nav class="site-state motion-element"><div class="site-state-item site-state-posts"> <a href="/archives/"><span class="site-state-item-count">37</span> <span class="site-state-item-name">日志</span></a></div><div class="site-state-item site-state-categories"> <a href="/categories/index.html"><span class="site-state-item-count">11</span> <span class="site-state-item-name">分类</span></a></div><div class="site-state-item site-state-tags"> <a href="/tags/index.html"><span class="site-state-item-count">10</span> <span class="site-state-item-name">标签</span></a></div></nav><div class="feed-link motion-element"><a href="/atom.xml" rel="alternate"><i class="fa fa-rss"></i> RSS</a></div><div class="links-of-author motion-element"><span class="links-of-author-item"><a href="https://gitee.com/King-XiYu" target="_blank" title="Gitee"><i class="fa fa-fw fa-hand-o-right"></i> Gitee</a></span><span class="links-of-author-item"><a href="https://github.com/King-XiYu" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i> GitHub</a></span></div><div class="links-of-blogroll motion-element links-of-blogroll-inline"><div class="links-of-blogroll-title"><i class="fa fa-fw fa-link"></i> Links</div><ul class="links-of-blogroll-list"><li class="links-of-blogroll-item"> <a href="https://www.baidu.com/" title="度娘" target="_blank">度娘</a></li><li class="links-of-blogroll-item"> <a href="https://www.google.com/" title="Google" target="_blank">Google</a></li></ul></div></div></section><section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active"><div class="post-toc"><div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#使用-typeof-bar-quot-object-quot-来确定bar是否是对象的潜在陷阱是什么-怎样才能避免这个陷阱呢"><span class="nav-number">1.</span> <span class="nav-text">使用 typeof bar &#x3D;&#x3D;&#x3D; &quot;object&quot; 来确定bar是否是对象的潜在陷阱是什么?怎样才能避免这个陷阱呢?</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#下面的代码将输出什么到控制台，为什么？"><span class="nav-number">2.</span> <span class="nav-text">下面的代码将输出什么到控制台，为什么？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#下面的代码将输出什么到控制台，为什么？-1"><span class="nav-number">3.</span> <span class="nav-text">下面的代码将输出什么到控制台，为什么？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#将JavaScript源文件的整个内容包装在函数块中的意义和原因是什么？"><span class="nav-number">4.</span> <span class="nav-text">将JavaScript源文件的整个内容包装在函数块中的意义和原因是什么？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#在JavaScript源文件开头包含use-strict的意义和好处是什么？"><span class="nav-number">5.</span> <span class="nav-text">在JavaScript源文件开头包含use strict的意义和好处是什么？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#考虑下面的两个函数。它们会返回相同的东西吗-为什么或为什么不？"><span class="nav-number">6.</span> <span class="nav-text">考虑下面的两个函数。它们会返回相同的东西吗?为什么或为什么不？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#NaN-是什么-它是什么类型的-如何可靠地测试一个值是否等于NaN"><span class="nav-number">7.</span> <span class="nav-text">NaN 是什么?它是什么类型的?如何可靠地测试一个值是否等于NaN?</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#下面的代码将输出什么-解释你的答案。"><span class="nav-number">8.</span> <span class="nav-text">下面的代码将输出什么?解释你的答案。</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#讨论如何编写一个isInteger-x-函数来确定x是否是整数。"><span class="nav-number">9.</span> <span class="nav-text">讨论如何编写一个isInteger(x)函数来确定x是否是整数。</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#执行以下代码时，数字1-4将以什么顺序记录到控制台？-为什么？"><span class="nav-number">10.</span> <span class="nav-text">执行以下代码时，数字1-4将以什么顺序记录到控制台？ 为什么？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#编写一个简单的函数-小于160个字符-，返回一个布尔值，指示字符串是否是回文。"><span class="nav-number">11.</span> <span class="nav-text">编写一个简单的函数(小于160个字符)，返回一个布尔值，指示字符串是否是回文。</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#编写一个-sum-方法，当使用以下两种语法调用时，该方法将正常工作。"><span class="nav-number">12.</span> <span class="nav-text">编写一个 sum 方法，当使用以下两种语法调用时，该方法将正常工作。</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#考虑以下代码片段：-a-当用户单击按钮4时，控制台记录了什么内容以及为什么？-b-提供一个或多个可按预期工作的替代实现。"><span class="nav-number">13.</span> <span class="nav-text">考虑以下代码片段：(a)当用户单击按钮4时，控制台记录了什么内容以及为什么？(b)提供一个或多个可按预期工作的替代实现。</span></a></li></ol></div></div></section><div class="back-to-top"><i class="fa fa-arrow-up"></i> <span id="scrollpercent"><span>0</span>%</span></div></div></aside></div></main><footer id="footer" class="footer"><div class="footer-inner"><div class="copyright">&copy; <span itemprop="copyrightYear">2020</span><span class="with-love"><i class="fa fa-user"></i></span> <span class="author" itemprop="copyrightHolder">宇宙特别帅</span></div></div></footer></div><script type="text/javascript">"[object Function]"!==Object.prototype.toString.call(window.Promise)&&(window.Promise=null)</script><script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script><script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script><script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script><script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script><script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script><script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script><script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script><script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script><script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script><script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script><script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script><script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script><script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script><script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script><script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script><script src="//cdn.jsdelivr.net/npm/valine/dist/Valine.min.js"></script><script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: true,
        appId: '9DODHXKj6rr1cK4oO07iVBX3-gzGzoHsz',
        appKey: 'aJaxxns4VN5WV9nMimT9aSb1',
        placeholder: 'ヾﾉ≧∀≦)o 来呀！吐槽一番吧！',
        avatar:'mp',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script><script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "./public/search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script><script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script><script>AV.initialize("9DODHXKj6rr1cK4oO07iVBX3-gzGzoHsz","aJaxxns4VN5WV9nMimT9aSb1")</script><script>function showTime(e){var t=new AV.Query(e),c=[],u=$(".leancloud_visitors");u.each(function(){c.push($(this).attr("id").trim())}),t.containedIn("url",c),t.find().done(function(e){var t=".leancloud-visitors-count";if(0!==e.length){for(var n=0;n<e.length;n++){var o=e[n],i=o.get("url"),s=o.get("time"),r=document.getElementById(i);$(r).find(t).text(s)}for(n=0;n<c.length;n++){i=c[n],r=document.getElementById(i);var l=$(r).find(t);""==l.text()&&l.text(0)}}else u.find(t).text(0)}).fail(function(e,t){console.log("Error: "+t.code+" "+t.message)})}function addCount(i){var e=$(".leancloud_visitors"),s=e.attr("id").trim(),r=e.attr("data-flag-title").trim(),t=new AV.Query(i);t.equalTo("url",s),t.find({success:function(e){if(0<e.length){var t=e[0];t.fetchWhenSave(!0),t.increment("time"),t.save(null,{success:function(e){$(document.getElementById(s)).find(".leancloud-visitors-count").text(e.get("time"))},error:function(e,t){console.log("Failed to save Visitor num, with error message: "+t.message)}})}else{var n=new i,o=new AV.ACL;o.setPublicReadAccess(!0),o.setPublicWriteAccess(!0),n.setACL(o),n.set("title",r),n.set("url",s),n.set("time",1),n.save(null,{success:function(e){$(document.getElementById(s)).find(".leancloud-visitors-count").text(e.get("time"))},error:function(e,t){console.log("Failed to create")}})}},error:function(e){console.log("Error:"+e.code+" "+e.message)}})}$(function(){var e=AV.Object.extend("Counter");1==$(".leancloud_visitors").length?addCount(e):1<$(".post-title-link").length&&showTime(e)})</script><script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.4/clipboard.min.js"></script><script type="text/javascript" src="/js/src/clipboard-use.js"></script></body></html>